<template>
  <div class>
    <div class="search">
      <div class="input">
        <p>
          <label>角色标识：</label>
          <el-input v-model="roleTags" placeholder="请输入编码"/>
        </p>
        <p>
          <label>角色名称：</label>
          <el-input v-model="roleName" placeholder="请输入手机号"/>
        </p>
        <p>
          <label>角色：</label>
          <el-select v-model="roleId" placeholder="请选择类型" class="set">
            <el-option label="请选择" value/>
            <el-option
              v-for="(val,key) in roleSearch"
              :key="val.key"
              :label="val.roleDescription"
              :value="val.roleId"
            />
          </el-select>
        </p>

        <p class="deat">
          <el-button type="primary" class="se" style="margin-left:10px;" @click="search">搜索</el-button>
        </p>
      </div>
    </div>
    <div class="add">
      <el-button type="primary" @click="dialogs">新增角色</el-button>
      <el-button type="primary" @click="compile">编辑角色</el-button>
      <el-button type="danger" @click="dels">批量删除</el-button>
    </div>
    <tableVue :list="list" :state="true" :total="total" @changeData="selectionVal">
      <slot>
        <el-table-column label="操作" align="center" width="200px;">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row,1)">权限</el-button>
            <el-button
              size="mini"
              type="danger"
              class="del"
              @click="handleEdit(scope.$index, scope.row,2)"
            >删除角色</el-button>
          </template>
        </el-table-column>
      </slot>
    </tableVue>
    <dialogVue :dialog="dialog" :state="false" title="操作角色" @close="changeData">
      <slot>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色标识" prop="identifying">
            <el-input v-model="ruleForm.identifying" placeholder="请输入标识"/>
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入名称"/>
          </el-form-item>
          <el-form-item label="描述" prop="content">
            <el-input v-model="ruleForm.content" placeholder="请输入描述"/>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" @click="submitForm('ruleForm')">创建</el-button>
            <!-- <el-button type="primary" @click="upForm('ruleForm')">更新</el-button> -->
          </el-form-item>
        </el-form>
      </slot>
    </dialogVue>

    <dialogVue :dialog="compileDialog" :state="false" title="编辑角色" @close="changeData">
      <slot>
        <el-form
          ref="ruleForms"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色标识" prop="identifying">
            <el-input v-model="ruleForm.identifying" placeholder="请输入标识"/>
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入名称"/>
          </el-form-item>
          <el-form-item label="描述" prop="content">
            <el-input v-model="ruleForm.content" placeholder="请输入描述"/>
          </el-form-item>
          <el-form-item class="confirm">
            <el-button type="primary" @click="compileConfirm('ruleForm')">更新</el-button>
          </el-form-item>
        </el-form>
      </slot>
    </dialogVue>

    <el-dialog :visible="limits" title="添加权限" width="80%">
      <div class="menu">
        <div class>
          <el-tree
            v-loading="pageData.loading"
            ref="tree"
            :data="data"
            :show-checkbox="true"
            :props="defaultProps"
            :highlight-current="true"
            check-strictly
            node-key="menuId"
            @node-click="handleNodeClick"
            @check="check_fn"
          />
        </div>

        <div class="dialog_content">
          <el-table
            ref="upTable"
            :data="Uplist.tbody"
            tooltip-effect="dark"
            style="width: 100%"
            @select-all="handleChange"
            @select="handleChange"
          >
            <el-table-column type="selection" width="80"/>
            <el-table-column
              v-for="(item,idx) in Uplist.thead"
              :label="item.label"
              :key="idx"
              align="center"
            >
              <template slot-scope="scope">{{ scope.row[item.prop] }}</template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="limits = false">取 消</el-button>
        <el-button type="primary" @click="upAddRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Data from './RoleData.js'
import dialogVue from '@/components/dialog.vue'
import tableVue from '@/components/alltable.vue'
import {
  addRole,
  searchList,
  del,
  roleMenu,
  operation,
  whatPermission,
  compileRole,
  addRoleMenu
} from '@/api/role/role'
import checkPermission from '@/utils/permission' // 权限判断函数
export default {
  components: {
    tableVue,
    dialogVue
  },
  data() {
    return JSON.parse(JSON.stringify(Data))
  },
  mounted() {
    this.roleList()
  },
  methods: {
    checkPermission,
    search() {
      // 搜索
      searchList(this.roleName, this.roleId, this.roleTags).then(res => {
        if (res.data.code == 'OK') {
          this.list.tbody = res.data.data.records
          this.$message.success('搜索成功')
        } else {
          this.$message.error('错误')
        }
      })
    },
    handleChange(selection) {
      //   this.selectList[this.currentSelectMenuIndex].operationList = val;
      // this.selectMenuChildList = selection;
      this.Uplist.tbody.map(item => {
        const index = this.selectMenuChildList.findIndex(t => { return t.operationId == item.operationId })
        if (index != -1) {
          this.selectMenuChildList.splice(index, 1)
        }
      })
      this.selectMenuChildList = this.selectMenuChildList.concat(selection)
    },
    roleList() {
      // 列表
      searchList().then(res => {
        if (res.data.code == 'OK') {
          this.list.tbody = res.data.data.records
          this.roleSearch = res.data.data.records
          this.total = res.data.data.pages
        } else {
          this.$message.error('错误')
        }
      })
    },
    upAddRole() {
      // 设置角色权限

      const datas = {
        permissions: [],
        roleId: this.RoleID
      }
      this.selectMenuList.map(item => {
        // if (item.childMenuList && item.childMenuList.length > 0) {
        // } else {
        datas.permissions.push({
          permissionId: item.menuId,
          permissionType: 'MENU'
        })
        // }
      })
      this.selectMenuChildList.map(item => {
        datas.permissions.push({
          permissionId: item.operationId ? item.operationId : item.permissionId,
          permissionType: 'OPERATION'
        })
      })
      datas.permissions = JSON.stringify(datas.permissions)

      addRoleMenu(datas).then(res => {
        if (res.data.code == 'OK') {
          this.limits = false
          this.$message.success('添加成功')
        } else {
          this.$message.error(res.data.message)
        }
      })
      // console.log(datas);
      //   console.log(this.selectMenuList); //保存的左边选中的信息，只取里面第一层的id
      //   console.log(this.selectMenuChildList); //保存的右边全部的选中信息
    },
    handleNodeClick(data) {
      // 点击节点
      const isSel = this.selectMenuList.some((item, index) => {
        if (item.menuId == data.menuId) {
          this.currentSelectMenuIndex = index
        }
        return item.menuId == data.menuId
      })
      if (isSel) {
        this.Uplist.tbody = data.operationList
        var t = setTimeout(() => {
          this.selectMenuChildList.forEach(row => {
            this.$refs.upTable.toggleRowSelection(row, true)
          })
          clearTimeout(t)
        }, 0)
      } else {
        this.Uplist.tbody = []
      }
    },
    check_fn(data, selNodes) { // 当复选框被点击的时候触发
      this.selectMenuList = selNodes.checkedNodes.concat()

      // 弹框里面拉取菜单对于的数据
      const isSel = selNodes.checkedNodes.some(item => {
        return item.menuId == data.menuId
      })
      if (isSel) {
        this.Uplist.tbody = data.operationList
      } else {
        this.Uplist.tbody = []
        if (data.operationList && data.operationList.length > 0) {
          // let selectChildList = this.selectMenuChildList.concat();
          this.selectMenuChildList.map((selChild, idx, self) => {
            data.operationList.map(child => {
              this.selectMenuChildList.map((selChild, idx, self) => {
                if (child.operationId == selChild.operationId) {
                  self.splice(idx, 1)
                }
              })
            })
          })
        }
      }
    },
    dialogs() {
      if (checkPermission('role_manager_add') == true) {
        this.dialog = true
        this.ruleForm = {}
      } else {
        this.$message.error('您没有权限添加')
      }
    },
    changeData(val) {
      this.dialog = val
      this.compileDialog = val
    },
    handleEdit(idx, item, num) {
      // 删除、添加
      this.Uplist.tbody = []
      if (num == 1 && checkPermission('role_manager_set_perm') == true) {
        this.limits = true
        this.selectMenuList = []
        this.selectMenuChildList = []
        this.RoleID = item.roleId
        this.pageData.loading = true
        roleMenu().then(res => {
          // 拉取菜单
          if (res.data.code == 'OK') {
            this.data = res.data.data
            whatPermission(item.roleId).then(res => {
              // 拉取这个角色所有权限
              if (res.data.code == 'OK') {
                // console.log(res);
                setTimeout(() => {
                  this.pageData.loading = false
                }, 1000)
                const _data = res.data.data.filter(
                  item => item.permissionType == 'MENU'
                )
                this.selectMenuChildList = res.data.data.filter(
                  item => item.permissionType == 'OPERATION'
                )
                const _key = _data.reduce((argument, item) => {
                  argument.push(item.permissionId)
                  return argument
                }, [])
                this.$refs.tree.setCheckedKeys(_key)
                this.selectMenuList = this.$refs.tree
                  .getCheckedNodes()
                  .concat()
                  .map(item => {
                    if (item.operationList && item.operationList.length > 0) {
                      this.selectMenuChildList = this.selectMenuChildList.map(
                        selChild => {
                          item.operationList.map(child => {
                            if (child.operationId == selChild.permissionId) {
                              selChild = child
                            }
                          })
                          return selChild
                        }
                      )
                    }
                    return item
                  })
              }
            })
          }
        })
      } else if (num == 2 && checkPermission('role_manager_del') == true) {
        this.dels()
      } else {
        this.$message.error('您没有权限')
      }
    },
    submitForm(formName) {
      // 新增角色
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const data = {
            roleTags: this.ruleForm.identifying,
            roleName: this.ruleForm.name,
            roleDescription: this.ruleForm.content
          }
          addRole(data).then(res => {
            if (res.data.code == 'OK') {
              this.$message.success('新建角色成功')
              this.dialog = false
              this.roleList()
            } else {
              this.$message.error(res.data.code)
            }
          })
        }
      })
    },
    upForm() {

    },
    selectionVal(data) {
      // 列表里面的多选框
      this.selectionID = data
    },
    dels() {
      // 删除角色
      if (checkPermission('role_manager_del') == true) {
        if (this.selectionID.length == 0) {
          this.$message.error('请选择要删除的角色')
        } else {
          let roleId = ''
          this.selectionID.map(item => {
            roleId += item.roleId + ','
            return item
          })
          this.delMessage(() => {
            del(roleId).then(res => {
              if (res.data.code == 'OK') {
                this.$message.success('删除角色成功')
                this.roleList()
              } else {
                this.$message.error(res.data.code)
              }
            })
          })
        }
      } else {
        this.$message.error('您没有权删除')
      }
    },
    compile() {
      // 编辑角色
      if (checkPermission('role_manager_edit') == true) {
        if (this.selectionID.length == 0) {
          this.$message.error('请选择要编辑的角色')
        } else {
          if (this.selectionID.length > 1) {
            this.$message.error('只能编辑一个角色')
          } else {
            this.compileDialog = true
            this.selectionID.map(item => {
              this.ruleForm.identifying = item.roleTags
              this.ruleForm.name = item.roleName
              this.ruleForm.content = item.roleDescription
              this.RoleID = item.roleId
            })
          }
        }
      } else {
        this.$message.error('您没有权限编辑')
      }
    },
    compileConfirm() {
      // 编辑确定
      this.$refs.ruleForms.validate(valid => {
        if (valid) {
          const data = {
            roleTags: this.ruleForm.identifying,
            roleName: this.ruleForm.name,
            roleDescription: this.ruleForm.content,
            roleId: this.RoleID
          }
          compileRole(data).then(res => {
            if (res.data.code == 'OK') {
              this.$message.success('编辑角色成功')
              this.dialog = false
            } else {
              this.$message.error(res.data.message)
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.search {
  width: 100%;
  background-color: #fff;
  padding: 20px;
  box-sizing: border-box;
  margin-top: 10px;
  display: flex;
}
.input {
  /* width: 300px; */
  display: flex;
  flex-wrap: wrap;
}
label {
  line-height: 40px;
  color: #333;
  margin: 0 10px;
}
.el-input {
  width: 200px;
  height: 20px;
}
.add {
  margin-top: 10px;
  padding-left: 14px;
}
.content label {
  display: inline-block;
  width: 150px;
  text-align: justify;
  text-align-last: justify;
  line-height: 0;
  font-size: 16px;
}
.content input {
  height: 24px;
}
.content p {
  /* margin: 10px 0; */
}
.deat {
  /* margin-top: 20px; */
}
.confirm {
  position: absolute;
  bottom: -1px;
  right: 100px;
}
.dels {
  margin-left: 10px;
}
.menu {
  display: flex;
  /* align-items: center; */
}
.el-tree {
  width: 280px;
  border: 1px solid #ccc;
  padding: 10px 10px;
  box-sizing: border-box;
}
.el-tree-node__content {
  height: 36px !important;
}
.el-dialog__body {
  padding-top: 6px !important;
}
.dialog_content {
  margin-left: 20px;
  width: 100%;
}
</style>
